import axios from 'axios'

export default function ajax(url = '', data = {}, type = 'GET') {
    return new Promise((resolve, reject) => {
        let promise
        if (type === 'GET') {
            var dataStr = ''
            Object.keys(data).forEach(key => {
                // console.log(key)
                // console.log(data[key])
                dataStr += key + '=' + data[key] + '&'
            })
            if (dataStr !== '') {
                var index = dataStr.lastIndexOf('&')
                dataStr = dataStr.substring(0, index)
                url = url + '?' + dataStr
            }
            promise = axios.get(url)
        } else {
            // post请求
            promise = axios.post(url, data)
        }

        promise.then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err)
        })
    })
}